package com.ctgu.chatapp

import com.ctgu.chatapp.Netty.NettyClient
import com.ctgu.chatapp.Netty.protocol.Message
import com.ctgu.chatapp.utils.Utils
import com.ctgu.chatapp.view.FriendChat
import java.util.*

class TaskTimer(val imsMsg: Message.IMSMsg) : Timer() {

    val task = Task(imsMsg)

    init {
        schedule(task, 2000, 2000)
    }

    class Task(val imsMsg: Message.IMSMsg) : TimerTask() {

        private var retryCount = 0

        override fun run() {
            if (!NettyClient.instance.channel!!.isActive) {
                TaskTimerManager.remove(imsMsg.head.timestamp)
                return
            }
            retryCount++
            if (retryCount >= 3) {
                try {
                    if (imsMsg.bodyType == Message.IMSMsg.BodyType.ChatRequest) {
                        if (Utils.friendID == imsMsg.head.toId) {
                            val message = android.os.Message()
                            message.what = 0
                            message.obj = imsMsg.head.toId
                            FriendChat.handler.sendMessage(message)
                        }
                    }
                } finally {
                    TaskTimerManager.remove(imsMsg.head.timestamp)
                    NettyClient.instance.connect()
                }
            } else {
                NettyClient.instance.channel!!.writeAndFlush(imsMsg)
            }
        }
    }
}